package com.ruoyi.web.service.impl;

import com.ruoyi.common.base.ai.domain.AIApiKey;
import com.ruoyi.common.base.ai.enums.AIApiKeyEnum;
import com.ruoyi.common.base.ai.mapper.AIApiKeyMapper;
import com.ruoyi.common.base.ai.mapstruct.AIApiKeyStruct;
import com.ruoyi.common.base.ai.vo.AIApiKeyCache;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.customize.util.CommonUtil;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.web.service.IAIApiKeyService;
import lombok.AllArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * apiKey管理Service业务层处理
 *
 * @author gdk
 * @date 2023-05-29
 */
@Service
@AllArgsConstructor
public class AIApiKeyServiceImpl implements IAIApiKeyService {
    private final AIApiKeyMapper aIApiKeyMapper;

    private final RedisTemplate<String, Object> redis;
    private final CommonUtil commonUtil;

    /**
     * 查询apiKey管理
     *
     * @param id apiKey管理主键
     * @return apiKey管理
     */
    @Override
    public AIApiKey selectAIApiKeyById(Long id) {
        return aIApiKeyMapper.selectAIApiKeyById(id);
    }

    /**
     * 查询apiKey管理列表
     *
     * @param aIApiKey apiKey管理
     * @return apiKey管理
     */
    @Override
    public List<AIApiKey> selectAIApiKeyList(AIApiKey aIApiKey) {
        List<AIApiKey> list = aIApiKeyMapper.selectAIApiKeyList(aIApiKey);
        list.forEach(i -> {
            i.setStatus(AIApiKeyEnum.Status.findName(i.getStatus()));
        });

        return list;
    }

    /**
     * 新增
     *
     * @param entity
     * @author gdk
     * @since 2023/5/29 19:39
     */
    @Override
    @Transactional(rollbackFor = Throwable.class)
    public void insertAIApiKey(AIApiKey entity) {
        commonUtil.initCreateAbout(entity);
        if (aIApiKeyMapper.insertAIApiKey(entity) != 1) {
            CommonUtil.throwError();
        }

        AIApiKeyCache cache = AIApiKeyStruct.INSTANCE.entity2Cache(entity);
        redis.opsForSet().add(CacheConstants.AI_API_KEY_HASH_KEY, cache);
    }

    /**
     * 批量逻辑删除
     *
     * @param ids ids
     * @author gdk
     * @since 2023/5/29 20:02
     */
    @Override
    @Transactional(rollbackFor = Throwable.class)
    public void removeLogicByIds(Long[] ids) {
        AIApiKey condition = new AIApiKey();
        commonUtil.initUpdateAbout(condition);

        List<AIApiKeyCache> list = aIApiKeyMapper.listCacheByIds(ids);
        // 批量逻辑删除
        if (aIApiKeyMapper.removeLogicByIds(ids, condition) != list.size()) {
            throw new ServiceException();
        }

        redis.opsForSet().remove(CacheConstants.AI_API_KEY_HASH_KEY, list.toArray());
    }
}
